﻿using System.Threading.Tasks;
using System.Xml.Linq;
using ERP.Common.Util.Service;
using ERP.SYS.Config;
using ERP.SYS.Interfaces;
using ERP.SYS.Model.Entity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using UERP.Common.Util.Model;

namespace ERP.SYS.BLL;

public class UserServiceImpl : BaseService<SysUser, ERPSysDbContext>, IUserService
{
    private readonly ILogger<UserServiceImpl> _logger;
    public UserServiceImpl(IServiceScopeFactory serviceScopeFactory, ILogger<UserServiceImpl> logger) : base(serviceScopeFactory)
    {
        _logger = logger;
    }

    public PagedList<SysUser> GetUsers(string name = "", int page = 1, int pageSize = 10)
    {
        using (var scope = _serviceScopeFactory.CreateScope())
        {
            using (var context = scope.ServiceProvider.GetRequiredService<ERPSysDbContext>())
            {
                var userQuery = context.SysUsers.AsQueryable();

                if (!string.IsNullOrEmpty(name))
                {
                    userQuery = userQuery.Where(v => v.Name.Contains(name));
                }

                var totalCount = userQuery.Count();

                var users = userQuery.Select(u => new SysUser
                {
                    UserId = u.UserId,
                    Name = u.Name,
                    CreateAt = u.CreateAt,
                    UpdateAt = u.UpdateAt,
                    IsDelete = u.IsDelete
                })
                    .OrderBy(v => v.UserId)
                    .Skip((page - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();

                return new PagedList<SysUser>
                {
                    Data = users,
                    Total = totalCount
                };
            }
        }
    }

    public async Task<SysUser> SelectNameAndPassword(string name, string password)
    {
        using (var scope = _serviceScopeFactory.CreateScope())
        {
            using (var context = scope.ServiceProvider.GetRequiredService<ERPSysDbContext>())
            {
                var userQuery = context.SysUsers.AsQueryable();

                var userEntity = await userQuery
                  .Where(v => v.Name.Equals(name) && v.Password.Equals(password))
                  .FirstOrDefaultAsync();

                return userEntity;
            }
        }
    }

    public async Task<SysUser> UserInfo(int userId)
    {
        using (var scope = _serviceScopeFactory.CreateScope())
        {
            using (var context = scope.ServiceProvider.GetRequiredService<ERPSysDbContext>())
            {
                var userQuery = context.SysUsers.AsQueryable();

                var userEntity = await userQuery
                  .Where(v => v.UserId.Equals(userId))
                  .FirstAsync();

                return userEntity;
            }
        }
    }
}
